Approach Set a selected option using [(ngModel)]

ngModel directive is used for two-way data binding. Here we are using ngModel to establish the two-way data binding between the variable of our component class and the selected option in the dropdown.

Syntax:

<select [(ngModel)]="selectedValue">
<option value="option1">Option 1 </option>
<option value="option2">Option 2 </option>
<option value="option3">Option 3 </option>
</select>

Here, we are binding `selectedValue` variable using ngModel , so we can update the selectedValue variable in our component file and set the dropdown list. Let us look into an example using this approach :

Example :

HTML
<!-- app.component.html -->

<select [(ngModel)]="color">
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="black">Black</option>
    <option value="white">White</option>
</select>
<p>Selected Color : {{ color }}</p>
JavaScript
//app.component.ts

import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
})
export class AppComponent {
    color: string = 'red';
}

Output:

Here we gave the default value as ‘red’ for variable `color` which we used for 2 way data binding using ngModel. Hence the coolor red is selected by default in the dropdown. Since it is a two-way data binding, whenever there is change of option selected, it is updating the color variable as well.

How to set a Selected Option of a Dropdown List control using Angular ?

In Angular, a select or dropdown list is a common UI component that allows users to choose a single value from a predefined set of options. Angular select allows us to bind the dropdown list to a data source, such as an array or an object, using directives like `*ngFor`. It allows 2-way data binding using [(ngModel)] directive. Angular also provides us with Event Handling functions like (change), (selectionChange), etc, which allows us to handle events triggered by the dropdown list such as changing the selected option.

In this article, we will see how to set a selected option of a dropdown list control.

Table of Content

  • Set a selected option using [(ngModel)]
  • Set a selected option using [selected] property

Similar Reads

Approach 1. Set a selected option using [(ngModel)]

ngModel directive is used for two-way data binding. Here we are using ngModel to establish the two-way data binding between the variable of our component class and the selected option in the dropdown....

Approach 2. Set a selected option using [selected] property

Here we will be using [selected] property binding on each option, to set the selected option based on the condition. Here we directly set the selected attribute on each option element based on a comparison with the selectedValue property in our component. This approach is simpler and only requires setting the initial selected value....